﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MaintenanceService.Common.Scheduler
{
    public class ServiceSchedulerDefault : ServiceScheduler
    {
      /// <summary>
      /// This is the default time for the service to sleep if there are no pending tasks.
      /// </summary>
        public static readonly int SleepingTimeWithoutPendingTasks = 15;

  
        /// <summary>
        /// This is the limit the service will sleep if there are pendings tasks.
        /// </summary>
        public static readonly int SleepingTimeLimitWithPendingTasks = 120;

        /// <summary>
        /// Gets the service sleep time.
        /// <ul>
        /// <li>If there are no pending tasks, The Service Sleeps for [SleepingTimeWithoutPendingTasks].</li>
        /// <li>If there are pendings tasks, The Service Sleeps as much as it takes the last task to run.
        /// For Example if the last task if previos task was takes 4 seconds to run the Service sleeps 4 seconds.
        /// This is to prevent the blocking of the system.</li>
        /// <li>Under no circumstances The Service sleeps more than [SleepingTimeLimitWithPendingTasks] seconds.</li>
        /// </ul>
        /// </summary>
        /// <param name="arg">Decide next sleeping time.</param>
        /// <returns>Seconds the service must sleeep.</returns>
        public override int GetServiceSleepTime(ServiceSchedulerArgs arg)
        {
            if (arg == null)
            {
                return SleepingTimeWithoutPendingTasks;
            }
            if (!arg.ArePendingTasks)
            {
                return SleepingTimeWithoutPendingTasks;
            }
            else
            {
                int interval = SleepingTimeLimitWithPendingTasks;

                return (arg.LastTaskDuration > interval) ? interval : arg.LastTaskDuration;
            }
        }
    }
}
